import React from 'react';
import { StyleSheet, ViewStyle, StyleProp, ScrollViewProps, Dimensions } from 'react-native';
import Animated, {
  useAnimatedScrollHandler,
  useAnimatedStyle,
  useSharedValue,
  interpolate,
  Extrapolate,
} from 'react-native-reanimated';

const { height: SCREEN_HEIGHT } = Dimensions.get('window');

interface ParallaxScrollViewProps extends ScrollViewProps {
  headerHeight?: number;
  parallaxHeight?: number;
  renderHeader: () => React.ReactNode;
  children: React.ReactNode;
  style?: StyleProp<ViewStyle>;
  contentContainerStyle?: StyleProp<ViewStyle>;
}

export function ParallaxScrollView({
  headerHeight = 300,
  parallaxHeight = 0.5, // 视差效果强度（0-1）
  renderHeader,
  children,
  style,
  contentContainerStyle,
  ...scrollViewProps
}: ParallaxScrollViewProps) {
  const scrollY = useSharedValue(0);

  const scrollHandler = useAnimatedScrollHandler({
    onScroll: (event) => {
      scrollY.value = event.contentOffset.y;
    },
  });

  const headerAnimatedStyle = useAnimatedStyle(() => {
    const translateY = interpolate(
      scrollY.value,
      [0, headerHeight],
      [0, -headerHeight * parallaxHeight],
      Extrapolate.CLAMP
    );

    const scale = interpolate(
      scrollY.value,
      [0, headerHeight],
      [1, 1 + parallaxHeight],
      Extrapolate.CLAMP
    );

    return {
      transform: [
        { translateY },
        { scale },
      ],
    };
  });

  return (
    <Animated.ScrollView
      style={[styles.container, style]}
      contentContainerStyle={[
        styles.contentContainer,
        { paddingTop: headerHeight },
        contentContainerStyle,
      ]}
      onScroll={scrollHandler}
      scrollEventThrottle={16}
      {...scrollViewProps}
    >
      <Animated.View
        style={[
          styles.headerContainer,
          {
            height: headerHeight,
            top: 0,
          },
          headerAnimatedStyle,
        ]}
      >
        {renderHeader()}
      </Animated.View>
      {children}
    </Animated.ScrollView>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
  } as ViewStyle,
  contentContainer: {
    flexGrow: 1,
  } as ViewStyle,
  headerContainer: {
    position: 'absolute',
    left: 0,
    right: 0,
    overflow: 'hidden',
  } as ViewStyle,
});
